package com.binfenhulian.chinaenergy.ces.manage.core.url2io.processor.download;

import com.binfenhulian.chinaenergy.ces.core.exception.BaseException;
import com.binfenhulian.chinaenergy.ces.manage.core.oss.service.OSSService;
import com.binfenhulian.chinaenergy.ces.utils.file.FileUtils;
import com.binfenhulian.chinaenergy.ces.utils.uuid.UuidUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * Created by wanghjbuf on 2018/3/19.
 */
@Service("com.binfenhulian.chinaenergy.ces.manage.core.url2io.processor.download.DownloadImagService")
public class DownloadImagService {

    @Resource(name = "com.binfenhulian.chinaenergy.ces.manage.core.oss.service.OSSServiceImpl")
    OSSService oSSService;

    /**
     * 文件下载
     * @param sourceAddr
     * @param destDesc
     * @throws BaseException
     */
    public String download(String sourceAddr, String destDesc) throws BaseException{
        HttpClient client = new HttpClient();

        GetMethod method=new GetMethod(sourceAddr);
        try {
            Header accept = new Header("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            Header accept_encoding = new Header("Accept-Encoding","gzip, deflate, sdch");
            Header accept_language = new Header("Accept-Language","zh-CN,zh;q=0.8");
            Header connection = new Header("Connection","keep-alive");
            Header insecure = new Header("Upgrade-Insecure-Requests","1");
            Header user_agent = new Header("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");

            method.setRequestHeader(accept);
            method.setRequestHeader(accept_encoding);
            method.setRequestHeader(accept_language);
            method.setRequestHeader(connection);
            method.setRequestHeader(insecure);
            method.setRequestHeader(user_agent);
            client.executeMethod(method);

            if (method.getStatusCode() == HttpStatus.SC_OK) {
                byte[] imgByte = method.getResponseBody();
                InputStream in = new ByteArrayInputStream(imgByte);

                File file=new File(destDesc, FileUtils.getFileNameByPath(sourceAddr));
                FileOutputStream fos=new FileOutputStream(file);
                byte[] b = new byte[1024];
                int nRead = 0;
                while ((nRead = in.read(b)) != -1) {
                    fos.write(b, 0, nRead);
                }
                fos.flush();
                fos.close();
                in.close();

                return new StringBuffer(destDesc).append("/").append(FileUtils.getFileNameByPath(sourceAddr)).toString();
            }else{
               throw new BaseException("文件下载过程返回码错误,操作失败");
            }
        } catch (Exception e) {
            throw new BaseException("文件下载过程发生未知错误,操作失败", e);
        }finally {
            method.releaseConnection();
        }
    }

    /**
     * 文件转存
     * @param sourceAddr
     * @return
     * @throws BaseException
     */
    public String transform(String sourceAddr) throws BaseException{
        HttpClient client = new HttpClient();

        String objectKey = UuidUtils.getUUID();
        GetMethod method=new GetMethod(sourceAddr);
        try {
            Header accept = new Header("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            Header accept_encoding = new Header("Accept-Encoding","gzip, deflate, sdch");
            Header accept_language = new Header("Accept-Language","zh-CN,zh;q=0.8");
            Header connection = new Header("Connection","keep-alive");
            Header insecure = new Header("Upgrade-Insecure-Requests","1");
            Header user_agent = new Header("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");

            method.setRequestHeader(accept);
            method.setRequestHeader(accept_encoding);
            method.setRequestHeader(accept_language);
            method.setRequestHeader(connection);
            method.setRequestHeader(insecure);
            method.setRequestHeader(user_agent);
            client.executeMethod(method);

            if (method.getStatusCode() == HttpStatus.SC_OK) {
                byte[] imgByte = method.getResponseBody();
                String filePath = oSSService.upLoadFile("url2io", objectKey, imgByte);
                return oSSService.getTempAccessUrlForWithPub(filePath);
            }else{
                throw new BaseException("文件转存过程返回码错误,操作失败");
            }
        } catch (Exception e) {
            throw new BaseException("文件转存过程发生未知错误,操作失败", e);
        }finally {
            method.releaseConnection();
        }
    }
}
